<?php
/**
 * Created by PhpStorm.
 * User: 12133
 * Date: 2023/2/17
 * Time: 10:30
 */

namespace app\middleware;


use think\Response;

class Sign
{
    private $controller = ['User','Address','Order'];//需要登录验证的控制器
//    private $action = [''];//需要登录跳过验证的方法
    private $login = [];//需要登录后使用的方法
    /**
     * ApiAuth鉴权
     * @param \think\facade\Request $request
     * @param \Closure $next
     * @return mixed|\think\response\Json
     */
    public function handle($request, \Closure $next): Response {
        if (strtoupper($request->method()) == "OPTIONS")
            return json(['code' => 200, 'msg'  => '', 'data' => []],200);
        $ApiAuth = header('ApiAuth', '');
        $controller = str_replace('api.','',\think\facade\Request::controller());
        $action = \think\facade\Request::action();
        $action = $controller.'/'.$action;
        $login = in_array($action,$this->login) || in_array($controller,$this->controller);
        if (!empty($ApiAuth))
            $userInfo = cache($ApiAuth);
        if($login) {
            if (empty($userInfo))
                return json(['code' => 401, 'msg' => '该接口需要登录后使用', 'data' => []], 401);
            global $user;
            $user = \app\model\User::where('id', $userInfo->id)->find();
            if (empty($user->id))
                return json(['code' => 401, 'msg' => '账号不存在', 'data' => []], 401);
            // if ($user->token != $ApiAuth)
            //     return json(['code' => 401, 'msg' => '检测到账号在其他地点登录', 'data' => []], 401);
            if ($user->status == 2)
                return json(['code' => 401, 'msg' =>  '您已经被拉黑无法再正常使用了,请联系管理人员'],401);
        }else{
            global $user;
            $user = ['id' => 0];
            if (!empty($userInfo)) $user = \app\model\User::where('id', $userInfo->id)->find();
        }
        return $next($request);
    }
}